package com.hbck.bspatch

import android.os.Bundle
import android.os.Environment
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Toast
import java.io.File
import java.net.URL

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (getVersionCode() < 2) {
            Log.d("tim", "当前版本号小于2 进行更新")
            doBspatchTask()
        }


//        bsDiff()

    }

    private fun bsDiff() {
        Thread {
//            val oldPath = this@MainActivity.getApkSourceDir(com.hbck.bspatch.PACKAGE_NAME)
            val oldPath = SD_CARD + "old2.apk"
            val newPath = SD_CARD + "new2.apk"
            val patchPath = SD_CARD + "apk2.patch"
            Log.e("main--", "开始---"+patchPath)
            BsPatch.bsDiff(oldPath, newPath, patchPath)
            Log.e("main--", "结束---")
            runOnUiThread {
                Toast.makeText(this@MainActivity, "success", Toast.LENGTH_LONG)
            }
        }.start()
    }

    private fun doBspatchTask() {
        Thread {
            val bytes = URL(URL_PATH_DOWNLOAD).readBytes()
            val patchFile = File(Environment.getExternalStorageDirectory(), PATCH_FILE)
            if (patchFile.exists()) {
                patchFile.delete()
            }
            patchFile.writeBytes(bytes)

            val oldPath = this@MainActivity.getApkSourceDir(com.hbck.bspatch.PACKAGE_NAME)
            Log.e("main--", oldPath + "旧文件是否存在：" + File(oldPath).exists());
//            val oldPath = SD_CARD + "old2.apk"
            val newPath = NEW_APK_PATH

            BsPatch.bsPatch(oldPath, newPath, patchFile.absolutePath)

            runOnUiThread {
                this@MainActivity.installApk(newPath)
            }
        }.start()
    }

}
